<?php
namespace Admin\Controller;
use Admin\Model\NewsModel;
use Admin\Model\CommonModel;
use Think\Page;
class NewsController extends BaseController{
  public function index(){
  	//分页相关开始
  	$model=new NewsModel();
  	$common=new CommonModel();
  	$listRows=10;												//每页记录数
  	$totalRows=$common->count('news');							//总记录
  	$pn=I('get.p') ? I('get.p'):1;								//第几页.无页码是默认第一页
  	if (!is_numeric($pn)) $this->error('页码参数错误，必须为数字！');	//容错机制
  	$data=$model->get_news($pn,$listRows);						//按页获取记录
  	$page=new Page($totalRows,$listRows);
  	$show=$page->show();
  	$this->assign('data',$data);
  	$this->assign('page',$show);
  	$this->assign('title','新闻管理');
  	$this->display();
  }
  
  //新闻分类管理
  public function type(){
  	$type=new NewsModel();
  	$data=$type->get_type();
  	$this->assign('data',$data);
  	$this->assign('title','分类管理');
  	$this->display();
  }
  
  //新增资讯
  public function news(){
  	$news=new NewsModel();
  	if (IS_POST) {
  		$news->addNews()==1 ? $this->success('添加成功！',U('News/index')) : $this->error('添加失败，请刷新后重试');
  	}else{
  		$data=$news->get_type(false);
  		$this->assign('data',$data);
  		$this->assign('title','添加资讯');
  		$this->display();
  	}

  }
  //修改编辑分类
  public function modtype(){
  	if (IS_GET) {
  		$id=I('get.id');
  		$name=I('get.name');
  		$rs=M('news_type')->where(array('name'=>$name,'id'=>array('neq',$id)))->find();
  		if (is_array($rs)) {
  			die(0);
  		}else{
  			M('news_type')->where(array('id'=>$id))->save(array('name'=>$name));
  			echo mysql_affected_rows()==1 ? 1:0;die();
  		}
  		
  		
  	}	
  }
  
  //新增分类
  public function addtype(){
  	if (IS_POST){
  		$news=new NewsModel();
  		$news->add_type(I('post.content'))==1 ? $this->success('分类添加成功'):$this->error('分类添加失败，请刷新页面后重试');
  	}
  }
  
  //删除分类
  public function delete_type(){
  	$common=new CommonModel();
  	M('news')->where(array('tid'=>I('get.id')))->delete();
  	$common->delete('news_type', I('get.id'))==1 ? $this->success('删除成功。') : $this->error('未知错误，删除失败，请刷新页面后重试');
  }
  
  //删除新闻
  public function delete_news(){
  	$common=new CommonModel();
  	$common->delete('news', I('get.id'))==1 ? $this->success('删除成功！') : $this->error('删除失败');
  }
  
  public function edit(){
  	if (IS_POST) {
  		$news=new NewsModel();
  		$news->edit()==1 ? $this->success('修改成功！',U('News/index')) : $this->error('修改失败，请刷新后重试');;
  	}else{
  		$newsModel=new NewsModel();
  		$data=$newsModel->getNewsContent(I('get.id'));
  		$type=M('news_type')->select();
		$data['content']=html_entity_decode($data['content']);
  		$this->assign('data',$data);
  		$this->assign('type',$type);
  		$this->assign('title','编辑资讯');
  		$this->display();
  	}
  }
  
  
  
}
